import React, { Component } from 'react';
import { Card, Table } from 'antd';
import { connect } from 'dva';
import { saveAs } from 'file-saver';
import styles from './index.less';
import StandardTable from '@/components/StandardTable';
import SearchForm from '../../SystemInit/OrgSetting/SearchForm';
import BaseComponent from '@/components/BaseComponent';
import ToDoctor from './ToDoctor'
import PatientSide from './PatientSide'

@connect(({ user, orgsetting, loading }) => ({
  currentUser: user.currentUser,
  data: orgsetting.data,
  isLoading: loading.effects['orgsetting/listAllData'],
}))

class OrgSetting extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRowKeys: [],
      // 省份集合
      provinces: [],
      // 城市集合
      cities: [],
      // 区县集合
      districtAndStreet: [],
      // 搜索条件
      searchCondition: {},
    };
  }

  columns = [
    {
      title: '机构编码',
      // width: 180,
      sorter: false,
      key: 'org_code',
      dataIndex: 'org_code',
      // fixed: 'left',
    },
    {
      title: '机构类型',
      sorter: false,
      key: 'ext_flag',
      render: (text, record, index) => {
        const { ext_flag } = record;
        let type = '';
        if (ext_flag == '1') {
          type = '管理机构';
        } else if (ext_flag == '2') {
          type = '筛查机构';
        }
        return <span>{type}</span>;
      },
    },
    {
      title: '机构名称',
      sorter: false,
      dataIndex: 'org_name',
      key: 'org_name',
    },
    {
      title: '隶属省份',
      sorter: false,
      dataIndex: 'province_name',
      key: 'province_name',
    },
    {
      title: '隶属城市',
      sorter: false,
      dataIndex: 'city_name',
      key: 'city_name',
    },
    {
      title: '隶属区县',
      sorter: false,
      dataIndex: 'region_name',
      key: 'region_name',
    },
    {
      title: '详细地址',
      sorter: false,
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
        <div>
          <ToDoctor record={record} source="1" />
          <PatientSide record={record} source="2" />
        </div>
      ),
    },
  ];

  componentDidMount() {
    this.getAllProvince();
    this.listAllByPage({});
  }

  listAllByPage = params => {
    this.execHttp('orgsetting/listAllData', {
      currentPage: 1,
      pageSize: 10,
      user: this.props.currentUser.id,
      ...params,
    });
  };

  /** 点击获取所有省份 */
  getAllProvince = () => {
    this.execHttp('orgsetting/getAllProvince', {}).then(resp => {
      const { data, success } = resp;
      if (success) {
        this.setState({
          provinces: data.list,
        });
      }
    });
  };

  /** 点击获取省下面的城市 */
  getAllCities = val => {
    this.execHttp('orgsetting/getAllProvinceCity', {
      parentRegionCode: val,
    }).then(resp => {
      const {
        success,
        data: { list },
      } = resp;
      this.setState({
        cities: list,
      });
    });
  };

  /** 获取城市下的区街道信息 */
  getDistrictAndStreet = val => {
    this.execHttp('orgsetting/getDistrictAndStreet', {
      parentRegionCode: val,
    }).then(resp => {
      const {
        success,
        data: { list },
      } = resp;
      if (success) {
        this.setState({
          districtAndStreet: list,
        });
      }
    });
  };

  /** 导出页面的所有数据 */
  exportOrgData = params => {
    const hide = this.loadingMessage('正在导出数据,请稍后...');
    this.execHttp('orgsetting/exportOrgData', {
      user: this.props.currentUser.id,
      ...params,
    })
      .then(response => {
        hide();
        saveAs(response, '机构数据汇总' + '.xlsx');
      })
      .catch(error => {
        hide();
      });
  };

  render() {
    const { selectedRowKeys } = this.state;
    const { isLoading, data } = this.props;

    return (
      <div className={styles.orgSetting}>
        <Card size="small" bordered title="风险因素上报二维码">
          <SearchForm
            provinceList={this.state.provinces}
            cityList={this.state.cities}
            districtAndStreetList={this.state.districtAndStreet}
            onSearchClick={this.handleOnSearchClick}
            onResetClick={this.handleOnResetClick}
            onExportClick={this.handleOnExportClick}
            onSelectedProvince={this.handleOnSelectedProvince}
            OnSelectedCity={this.handleOnSelectedCity}
          />
          <div>
            {isLoading ? (
              <Table
                dataSource={[]}
                pagination={{}}
                columns={this.columns}
                onChange={this.handleTableChange}
                loading={isLoading}
                size="small"
                style={{marginTop:'20px'}}
              />
            ) : (
              <StandardTable
                hasSelection={false}
                selectedRows={selectedRowKeys}
                loading={isLoading}
                data={data}
                columns={this.columns}
                onChange={this.handleTableChange}
                rowKey="id"
                size="small"
                style={{marginTop:'20px'}}
              />
            )}
          </div>
        </Card>
        {/* <Card className={styles.contentBox}>
        </Card> */}
      </div>
    );
  }

  /**
   * 查询
   * @param data
   */
  handleOnSearchClick = data => {
    this.setState({
      searchCondition: data,
    });
    this.listAllByPage(data);
  };

  /**
   * 重置
   */
  handleOnResetClick = () => {
    this.listAllByPage();
  };

  /**
   * 导出
   */
  handleOnExportClick = () => {
    this.exportOrgData(this.state.searchCondition);
  };

  /**
   * tableChange
   * @param pagination
   * @param filtersArg
   * @param sorter
   */
  handleTableChange = (pagination, filtersArg, sorter) => {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.listAllByPage(params);
  };

  /**
   * 获取省份下的城市
   * */
  handleOnSelectedProvince = value => {
    if (value !== undefined) {
      this.getAllCities(value);
    }
  };

  /**
   * 获取城市下的区街道信息
   * */
  handleOnSelectedCity = value => {
    if (value !== undefined) {
      this.getDistrictAndStreet(value);
    } else {
      this.setState({
        districtAndStreet: [],
      });
    }
  };
}

export default OrgSetting;
